const { onPageNotFound } = require("../utils/err_util")
const controller = require("../controllers/goods")
const { getReqBody } = require("../utils/http_util");

async function handleGoodsRequest(req, res) {
    const regPath = /^\/goods\/(.*)$/
    const path = regPath.exec(req.url)[1]
    const rePage = /^\/goods\/list\/(\d+)$/
    const reGoodsId = /^\/goods\/([\da-z]{24})$/;

    let data = null;
    let body = null;
    try {
        switch (true) {
            // 添加商品
            case path === "0" && req.method === "POST":
                // res.end("添加商品成功")
                body = await getReqBody(req);
                data = await controller.addGoods(body);
                break;

                // 查询全部商品
            case path === "list/0" && req.method === "GET":
                // promise 版本
                // controller.getAllGoods()
                // .then(
                //     data=>res.end(JSON.stringify(data))
                // )
                // .catch(
                //     err=>res.end(JSON.stringify(err))
                // )

                // async+await 版本 （有await的函数，函数必须加上async）
                // try {
                //     const data = await controller.getAllGoods();
                //     res.end(JSON.stringify(data));
                // } 

                data = await controller.getAllGoods();
                break;

                // 分页查询商品
            case rePage.test(req.url) && req.method === "GET":
                data = await controller.getGoodsByPage(`${rePage.exec(req.url)[1]}`)
                break;

                // 修改商品
            case reGoodsId.test(req.url) && req.method === "PUT":
                body = await getReqBody(req);
                data = await controller.updataGoods(reGoodsId.exec(req.url)[1],body);
                break;

                // 删除商品
            case reGoodsId.test(req.url) && req.method === "DELETE":
                data = await controller.deleteGoods(reGoodsId.exec(req.url)[1]);
                break;

            default:
                onPageNotFound(req, res)
                break;
        }
        res.end(JSON.stringify(data));
    } catch(err) {
        res.end(JSON.stringify(err));
    }
}

module.exports = handleGoodsRequest